package com.guanghua.brick.db.extend.hibernate;

import java.util.Iterator;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.cfg.Configuration;
import org.springframework.orm.hibernate3.LocalSessionFactoryBean;

import com.guanghua.brick.util.FileUtil;

public class ExtendSpringLocalSessionFactoryBean extends LocalSessionFactoryBean {

	/**
	 * 重载父类的方法，加入对pkg的载入功能
	 */
	@Override
	protected void postProcessConfiguration(Configuration cfg) throws HibernateException {
		if (this.mappingPkgs != null) {
			for (int i = 0; i < this.mappingPkgs.length; i ++) {
				addPackageMapping(this.mappingPkgs[i], cfg);
			}
		}
	}
	
	
	/**
	 * 加载每一个目录下的所有hbm文件
	 * @param pkg
	 * @param cfg
	 */
	private void addPackageMapping(String pkg, Configuration cfg) {
		try {
			List list = FileUtil.searchFileFromClassPath(pkg, "[\\w]*.hbm.xml");
			Iterator iterator = list.iterator();
			while (iterator.hasNext()) {
				String file = iterator.next().toString();						
				try {
					cfg.addResource(file);
				} catch (Exception e) {
					logger.error("hibernate config: [" + file + "] not load success" );
				}
			}
		} catch (Exception e) {
			logger.error("search pkg to load hibernate config wrong", e);
		}
	}
	
	
	//属性设定
	private String[] mappingPkgs = null;
	public void setMappingPkgs(String[] mappingPkgs) {
		this.mappingPkgs = mappingPkgs;
	}
}
